package admin.data;

import java.util.ArrayList;
import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.DealEmailModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class DealEmailData {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "dealemail_";
	
	private int limit = 20;

	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public DealEmailData() {
		try {
			ObjectifyService.register(DealEmailModel.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
           //e.printStackTrace();
        }
		
        ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}
	
	public ArrayList<DealEmailModel> list() {
		ArrayList<DealEmailModel> deals = new ArrayList<DealEmailModel>();

		int start = (page - 1) * limit;
		Query<DealEmailModel> q = ofy.query(DealEmailModel.class).order("-date").limit(limit)
				.offset(start);
		for (DealEmailModel deal : q) {
			deals.add(deal);
		}

		return deals;
	}
	
	public DealEmailModel get(String id) {
		DealEmailModel page = new DealEmailModel();
		if (cache != null && cache.containsKey(prefix + id)) {
			page = (DealEmailModel) cache.get(prefix + id);
		} else {
			try {
				page = ofy.get(new Key<DealEmailModel>(DealEmailModel.class, id));
				cache.put(prefix + id, page);
			} catch (Exception e) {
				page = null;
			}
		}
		return page;
	}
	
	public void insert(DealEmailModel page) {
		if (cache != null) {
			cache.put(prefix + page.getId(), page);
		}
		ofy.put(page);
	}
	
	public void delete(DealEmailModel page) {
		if (cache != null && cache.containsKey(page.getId())) {
			cache.remove(prefix + page.getId());
		}
		ofy.delete(page);
	}
}
